<template>
  <Panel toggleable>
    <template #header>
      <div class="flex items-center gap-2">
        <span class="font-bold">Stream根配置</span>
      </div>
    </template>
    <Chip v-for="(i, index) in basicConfigs" :key="index">
      {{ i.code + '  ' + i.value + ';'
      }}<i class="pi pi-minus-circle" @click="basicConfigRemoveFn(i)" />
    </Chip>
    <Divider />
    <div class="flex gap-2">
      <basic-config-add
        :options="basicConfigOptions"
        @confirm="basicConfigAddFn"
      ></basic-config-add>
      <Button icon="pi pi-check" size="small" style="width: 120px" @click="addServerFn"
        >+ Server</Button
      >
      <Button icon="pi pi-check" size="small" style="width: 120px" @click="addStreamFn"
        >+ Stream</Button
      >
    </div>
  </Panel>
  <Divider />
  <Panel toggleable>
    <template #header>
      <SelectButton
        :allow-empty="false"
        optionLabel="name"
        v-model="serverOrStream"
        option-value="value"
        :options="serverStreamOptions"
        size="small"
      />
    </template>
    <stream-server-component
      v-show="serverOrStream === '1'"
      ref="serverRef"
    ></stream-server-component>
    <stream-upstream-component
      v-show="serverOrStream === '2'"
      ref="upstreamRef"
    ></stream-upstream-component>
  </Panel>
</template>
<script setup lang="ts">
import BasicConfigAdd from '@/views/tools/nginx/detail-comps/basic-config-add.vue'
import { ref, useTemplateRef } from 'vue'
import type { BasicConfig, StreamConfigDto } from '@/types/dt/Dt.ts'
import StreamServerComponent from '@/views/tools/nginx/detail-comps/stream-server-component.vue'
import StreamUpstreamComponent from '@/views/tools/nginx/detail-comps/stream-upstream-component.vue'

const serverRef = useTemplateRef('serverRef')
const upstreamRef = useTemplateRef('upstreamRef')

const basicConfigOptions = ref<{ name: string; code: string }[]>([
  { code: 'preread_timeout ', name: 'preread_timeout ' },
])
const basicConfigs = ref<BasicConfig[]>([])
function basicConfigAddFn(e: BasicConfig) {
  basicConfigs.value.push(e)
}
function basicConfigRemoveFn(e: BasicConfig) {
  basicConfigs.value = basicConfigs.value.filter((item) => item !== e)
}

const serverOrStream = ref('1')
const serverStreamOptions = [
  { name: 'Server', value: '1' },
  { name: 'UpStream', value: '2' },
]

function addServerFn() {
  serverRef.value?.addServer()
}
function addStreamFn() {
  upstreamRef.value?.addStream()
}

function getConfig(): StreamConfigDto {
  return {
    basicConfigs: basicConfigs.value,
    serverConfig: serverRef.value!.getConfig(),
    upstreamConfig: upstreamRef.value!.getConfig(),
  }
}

function setConfig(config: StreamConfigDto) {
  basicConfigs.value = config.basicConfigs || []
  serverRef.value!.setConfig(config.serverConfig || [])
  upstreamRef.value!.setConfig(config.upstreamConfig || [])
}
defineExpose({
  getConfig,
  setConfig,
})
</script>
<style scoped></style>
